package com.zzyq.pc.web.submit.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zzyq.pc.common.StandardDataFormat;
import com.zzyq.pc.common.base.BaseController;
import com.zzyq.pc.common.enums.RoleEnum;
import com.zzyq.pc.common.plugin.db.PageView;
import com.zzyq.pc.common.plugin.shiro.TokenManager;
import com.zzyq.pc.utils.HttpUtils;
import com.zzyq.pc.utils.LoggerUtils;
import com.zzyq.pc.web.configure.model.Depart;
import com.zzyq.pc.web.configure.service.IDepartService;
import com.zzyq.pc.web.submit.model.Submit;
import com.zzyq.pc.web.submit.service.ISubmitService;
import com.zzyq.pc.web.user.model.User;
import com.zzyq.pc.web.user.service.IUserService;

@Controller
@RequestMapping(value = "/submit/", produces = "application/json;charset=UTF-8")
public class SubmitController extends BaseController {
    @Autowired
    private ISubmitService submitService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IDepartService departService;

    /**
     * 发起报送
     * 
     * @param submit
     * @return
     */
    @ResponseBody
    @RequestMapping("post")
    public String post(HttpServletRequest httpRequest, HttpServletResponse response, Submit submit) {
        StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
        // 判断无效参数
        if (submit == null || StringUtils.isBlank(submit.getSubmitTitle()) || StringUtils.isBlank(submit.getSource())
                || StringUtils.isBlank(submit.getSubmitContent()) || submit.getInformationId() == null
                || submit.getReceiveUserId() == null || submit.getReceiveDepartId() == null) {
            return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
        }
        try {
            // 获得发起和接收用户的信息
            User postUser = TokenManager.getUser();
            List<User> rUsers = userService.selectForSubmit(submit.getReceiveUserId(), submit.getReceiveDepartId(),
                    postUser.getMaxRole().getRoleGrade(), RoleEnum.User_Com.getGrade());
            if (rUsers == null || rUsers.size() != 1) {
                return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
            }
            User receiveUser = rUsers.get(0);
            if (receiveUser.getCompany().getCompanyId().intValue() != postUser.getCompany().getCompanyId().intValue()) {
                return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
            }
            // 设置发起报送的部门和用户ID
            submit.setPostDepartId(postUser.getDepart().getDepartId());
            submit.setPostUserId(postUser.getUserId());
            // 设置其他的信息
            submit.setSubmitTitle(transString(httpRequest, submit.getSubmitTitle()));
            submit.setSource(transString(httpRequest, submit.getSource()));
            submit.setSubmitContent(transString(httpRequest, submit.getSubmitContent()));
            submit.setPostTime(new Date());
            submit.setSubmitState(0);
            boolean result = submitService.post(submit);
            if (!result) {
                return HttpUtils.formatData(format, CODE_ERROR, MSG_ERROR, null);
            }
            return HttpUtils.formatData(format, CODE_OK, MSG_OK, null);
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtils.fmtError(getClass(), "发起报送异常%s", e.getMessage());
            return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
        }
    }

    /**
     * 审核报送
     * 
     * @param submit
     * @return
     */
    @ResponseBody
    @RequestMapping("review")
    public String review(HttpServletRequest httpRequest, HttpServletResponse response, Submit submit) {
        StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
        if (submit == null || submit.getSubmitId() == null
                || (submit.getSubmitState() != 1 && submit.getSubmitState() != 2)
                || (submit.getSubmitState() == 2 && StringUtils.isBlank(submit.getSubmitReply()))) {
            return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
        }
        try {
            // 查询有效
            User activeUser = TokenManager.getUser();
            submit.setReceiveUserId(activeUser.getUserId());
            submit.setPostUserId(null);
            List<Submit> submits = submitService.selectAsList(null, submit, null);
            if (submits == null || !(submits.size() == 1)) {
                return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
            }
            Submit thisSubmit = submits.get(0);
            if (thisSubmit.getSubmitState() == 1 || thisSubmit.getSubmitState() == 2) {
                return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
            }
            // 进行修改
            Submit uSubmit = new Submit();
            uSubmit.setSubmitId(submit.getSubmitId());
            uSubmit.setSubmitReply(transString(httpRequest, submit.getSubmitReply()));
            uSubmit.setSubmitState(submit.getSubmitState());
            submit.setReviewTime(new Date());
            boolean result = submitService.review(uSubmit);
            if (!result) {
                return HttpUtils.formatData(format, CODE_ERROR, MSG_ERROR, null);
            }
            return HttpUtils.formatData(format, CODE_OK, MSG_OK, null);
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtils.fmtError(getClass(), "审核报送异常%s", e.getMessage());
            return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
        }
    }

    /**
     * 查询发起报送列表
     * 
     * @param submit
     * @return
     */
    @ResponseBody
    @RequestMapping("queryPost")
    public String queryPost(HttpServletRequest httpRequest, HttpServletResponse response, Integer pageIndex,
            Integer pageSize, Submit submit) {
        List<Submit> submits = new ArrayList<>();
        StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, submits);
        PageView pageView = null;
        try {
            // 设置分页参数
            if (pageIndex == null || pageIndex <= 0) {
                pageIndex = 1;
            }
            if (pageSize == null || pageSize <= 0) {
                pageSize = 10;
            }
            pageView = new PageView(pageSize, pageIndex);
            submit = new Submit();
            Integer companyId = null;
            User activrUser = TokenManager.getUser();
            if (!activrUser.getMaxRole().getRoleEnum().equals(RoleEnum.Admin_Com.getRole())) {
                submit.setPostUserId(activrUser.getUserId());
            } else {
                companyId = activrUser.getCompany().getCompanyId();
            }
            submits = submitService.selectAsList(pageView, submit, companyId);
            format.setPageIndex(pageView.getPageNow());
            format.setPageSize(pageView.getPageSize());
            format.setTotalPages(pageView.getPageCount());
            format.setTotalRecords(pageView.getRowCount());
            return HttpUtils.formatData(format, CODE_OK, MSG_OK, submits);
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtils.fmtError(getClass(), "查询报送列表异常%s", e.getMessage());
            return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, submits);
        }
    }

    /**
     * 查询审核报送列表
     * 
     * @param submit
     * @return
     */
    @ResponseBody
    @RequestMapping("queryReceive")
    public String queryReceive(HttpServletRequest httpRequest, HttpServletResponse response, Integer pageIndex,
            Integer pageSize, Submit submit) {
        List<Submit> submits = new ArrayList<>();
        StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, submits);
        PageView pageView = null;
        try {
            // 设置分页参数
            if (pageIndex == null || pageIndex <= 0) {
                pageIndex = 1;
            }
            if (pageSize == null || pageSize <= 0) {
                pageSize = 10;
            }
            pageView = new PageView(pageSize, pageIndex);
            submit = new Submit();
            User activrUser = TokenManager.getUser();
            submit.setReceiveUserId(activrUser.getUserId());
            submits = submitService.selectAsList(pageView, submit, null);
            format.setPageIndex(pageView.getPageNow());
            format.setPageSize(pageView.getPageSize());
            format.setTotalPages(pageView.getPageCount());
            format.setTotalRecords(pageView.getRowCount());
            return HttpUtils.formatData(format, CODE_OK, MSG_OK, submits);
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtils.fmtError(getClass(), "查询报送列表异常%s", e.getMessage());
            return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
        }
    }

    /**
     * 查询报送的上级用户列表
     */
    @ResponseBody
    @RequestMapping("queryUser")
    public String queryUser(HttpServletRequest httpRequest, HttpServletResponse response, Integer departId) {
        List<User> users = new ArrayList<>();
        StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, users);
        if (null == departId) {
            return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, users);
        }
        User user = TokenManager.getUser();
        Depart depart = new Depart();
        depart.setDepartId(departId);
        depart.setCompanyId(user.getCompany().getCompanyId());
        List<Depart> departs = departService.selectList(null, depart);
        if (null == departs || departs.isEmpty()) {
            return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, users);
        }
        try {
            users = userService.selectForSubmit(null, departId, user.getMaxRole().getRoleGrade(),
                    user.getMaxRole().getRoleGrade() - 50);
            return HttpUtils.formatData(format, CODE_OK, MSG_OK, users);
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtils.fmtError(getClass(), "查询用户列表异常%s", e.getMessage());
            return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, users);
        }
    }

    /**
     * 查询部门信息
     */
    @ResponseBody
    @RequestMapping("queryDepart")
    public String queryDepart(HttpServletRequest httpRequest, HttpServletResponse response) {
        List<Depart> departs = new ArrayList<>();
        StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, departs);
        User user = TokenManager.getUser();
        try {
            Depart qDepart = new Depart();
            qDepart.setCompanyId(user.getCompany().getCompanyId());
            departs = departService.selectList(null, qDepart);
            return HttpUtils.formatData(format, CODE_OK, MSG_OK, departs);
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtils.fmtError(getClass(), "查询部门列表异常%s", e.getMessage());
            return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, departs);
        }
    }
}
